import axios from "axios";
import { Loading } from 'element-ui';

let loadingInstance;

const http = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 10000 * 12,
});

// 默认携带Cookie
http.defaults.withCredentials = true;

http.interceptors.request.use(
  function (config) {
    loadingInstance = Loading.service({ fullscreen: true });
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

http.interceptors.response.use(
  function (response) {
    setTimeout(()=>{
       loadingInstance.close();
    },300)
    return response.data;
  },
  function (error) {
    setTimeout(()=>{
        loadingInstance.close();
    },300)
    return Promise.reject(error);
  }
);

function server(method, url, data, headers) {
  return http({
    url,
    method,
    params: method === "GET" ? data : null,
    data: method === "POST" ? data : null,
    timeout: 5000,
    headers: {
      "X-Requested-With": "XMLHttpRequest",
      accept: "application/json, text/plain, */*",
      ...headers,
    },
  });
}

export default {
  httpGet: (url, data) => server("GET", url, data),
  httpPost: (url, data, headers) => server("POST", url, data, headers),
};

